package com.neusoft.servlet;

import com.alibaba.fastjson.JSON;
import com.neusoft.dto.UserDto;
import com.neusoft.entity.UsersEntity;
import com.neusoft.mapper.UsersMapper;
import com.neusoft.utils.MyJWT;
import com.neusoft.utils.SqlSessionFactoryUtils;
import com.neusoft.vo.UserVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/users/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String jsonReq = IOUtils.toString(req.getInputStream(), StandardCharsets.UTF_8);
        UserDto userDto = JSON.parseObject(jsonReq, UserDto.class);


        SqlSessionFactory sqlSessionFactory
                = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
        UsersEntity usersEntity = usersMapper.loginUser(userDto.getUser());

        sqlSession.close();
        if(usersEntity != null){
            UserVo userVo = new UserVo();
            try {
                BeanUtils.copyProperties(userVo, usersEntity);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            System.out.println(usersEntity.getId().toString());
            Map<String,String> map = new HashMap<String, String>();
            map.put("userid", usersEntity.getId().toString());
            String jsonMap = JSON.toJSONString(map);
            String token = MyJWT.makeSecret(jsonMap);
            userVo.setToken(token);
            String jsonObject = JSON.toJSONString(userVo);
            PrintWriter printWriter = resp.getWriter();
            printWriter.println(jsonObject);
        }
        else{
            PrintWriter printWriter = resp.getWriter();
            printWriter.println("login failed");
        }


    }
}
